<template>
  <a-modal
    v-model:visible="modalVisible"
    @cancel="closeModal"
    width="600px"
    :top="100"
    :align-center="false"
    title="配置菜单角色权限"
    @ok="handleSubmit"
  >
    <template #footer>
      <a-button @click="closeModal">取消</a-button>
      <a-button type="primary" @click="handleSubmit">确定</a-button>
    </template>
    <a-form
      :rules="rules"
      :auto-label-width="true"
      :model="form.list"
      ref="formRef"
    >
      <a-form-item field="relIds" label="关联权限:" allow-clear>
        <a-cascader
          :field-names="fieldNames"
          :options="GetMenuData"
          v-model="form.list.relIds"
          check-strictly
          multiple
          :load-more="loadMore"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { getMenuList } from '@/apis/authManagement/index';
import { getRoleRelList } from '@/apis/roleManagement/index';
import { cloneDeep } from 'lodash';
const emit = defineEmits(['update:visible', 'setPermission']);
const fieldNames = { value: 'id', label: 'menuName' };
const GetMenuData = ref([]);
const getMenuData = async () => {
  try {
    const res = await getMenuList({ parentMenuId: 0 });
    const modules = import.meta.glob('@/views/Management/**/*');
    console.log(res, modules);
    GetMenuData.value = res.menuList;
  } catch (err: unknown) {
    console.log(err);
  }
};

const getRelData = async () => {
  const res = await getRoleRelList({
    sourcesId: props.masterRoleId,
    querySources: 1
  });
  if (res.list)
    res.list.forEach((element) => {
      form.list.relIds.push(element.menuId);
    });
};
getRelData();
const props = withDefaults(
  //参数说明
  defineProps<{
    masterRoleId: any; //修改的数据
    visible: boolean; //是否打开modal
  }>(),
  {
    visible: false
  }
);
// 控制确定取消按钮
const modalVisible = computed({
  //控制visible
  get() {
    return props.visible;
  },
  set() {
    return emit('update:visible', false);
  }
});

const form = reactive<any>({
  list: {
    relIds: [],
    masterType: 2,
    masterId: props.masterRoleId
  }
});

const loadMore = (option: any, done: any) => {
  window.setTimeout(async () => {
    const res = await getMenuList({ parentMenuId: option.id });
    await done(res.menuList);
  }, 1000);
};

const rules = {
  relIds: [{ required: true, message: '请选择关联权限' }]
};

//取消
const closeModal = () => {
  modalVisible.value = false;
  formRef.value.resetFields();
};
const formRef = ref();
const handleSubmit = async () => {
  //提交
  const check = await formRef.value.validate();
  if (!check) {
    emit('setPermission', cloneDeep(form.list));
    closeModal();
  }
};

onMounted(() => {
  getMenuData();
});
</script>
